import { Router } from "express";
import { authenticateWxAppToken } from "../middleware/wxapp-auth";
import { authenticateToken } from "../middleware/auth";

const router = Router();

// 存储用户位置数据（生产环境应使用数据库）
interface UserLocation {
  userId: string;
  username?: string;
  latitude: number;
  longitude: number;
  accuracy: number;
  timestamp: number;
  address?: string;
  floor?: string;
  department?: string;
  status: 'online' | 'offline';
  lastUpdate: string;
  deviceType?: 'wxapp' | 'mobile' | 'web';
  sessionId?: string;
}

// 位置需求数据
interface LocationRequest {
  id: string;
  userId: string;
  username?: string;
  type: 'navigation' | 'emergency' | 'appointment' | 'consultation';
  title: string;
  description: string;
  priority: 'low' | 'medium' | 'high' | 'critical';
  status: 'pending' | 'responding' | 'completed' | 'cancelled';
  timestamp: number;
  estimatedTime?: number;
}

// 内存存储（生产环境应使用Redis或数据库）
const userLocations = new Map<string, UserLocation>();
const locationRequests = new Map<string, LocationRequest>();

// 用户位置上报接口
router.post("/upload", authenticateWxAppToken, (req, res) => {
  try {
    const { latitude, longitude, accuracy, address, floor, department } = req.body;
    
    // 调试日志
    console.log('位置上报请求 - 用户信息:', req.user);
    console.log('位置上报请求 - wxUser信息:', req.wxUser);
    
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: "用户认证信息缺失"
      });
    }
    
    const userId = req.user.id;
    const username = req.user.username || req.user.name || userId;

    // 验证必要字段
    if (!latitude || !longitude) {
      return res.status(400).json({
        success: false,
        message: "经纬度坐标为必填项"
      });
    }

    // 验证坐标范围
    if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) {
      return res.status(400).json({
        success: false,
        message: "坐标值无效"
      });
    }

    const location: UserLocation = {
      userId,
      username,
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
      accuracy: accuracy || 10,
      timestamp: Date.now(),
      address,
      floor,
      department,
      status: 'online',
      lastUpdate: new Date().toISOString(),
      deviceType: 'wxapp',
      sessionId: (req as any).sessionID || 'unknown'
    };

    // 存储位置数据
    userLocations.set(userId, location);
    console.log(`✅ 用户位置已存储: ${username} (${userId}) - [${latitude}, ${longitude}]`);
    console.log(`📍 当前存储的位置总数: ${userLocations.size}`);
    console.log(`🗺️  所有用户位置:`, Array.from(userLocations.values()).map(loc => ({
      userId: loc.userId,
      username: loc.username,
      lat: loc.latitude,
      lng: loc.longitude,
      timestamp: new Date(loc.timestamp).toLocaleString()
    })));

    res.json({
      success: true,
      message: "位置更新成功",
      data: {
        userId,
        timestamp: location.timestamp,
        accuracy: location.accuracy
      }
    });
  } catch (error) {
    console.error("位置上报失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取所有在线用户位置（大屏端使用）
router.get("/users", authenticateToken, (req, res) => {
  try {
    const { online, department, floor } = req.query;
    
    console.log(`🔍 大屏端请求位置数据，参数:`, { online, department, floor });
    console.log(`📊 当前存储的位置总数: ${userLocations.size}`);
    
    let locations = Array.from(userLocations.values());
    
    // 过滤条件
    if (online === 'true') {
      const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
      const beforeFilter = locations.length;
      locations = locations.filter(loc => 
        loc.status === 'online' && loc.timestamp > fiveMinutesAgo
      );
      console.log(`⏰ 过滤在线用户: ${beforeFilter} -> ${locations.length} (5分钟内活跃)`);
    }
    
    if (department) {
      locations = locations.filter(loc => loc.department === department);
      console.log(`🏥 按科室过滤: ${locations.length} 个结果`);
    }
    
    if (floor) {
      locations = locations.filter(loc => loc.floor === floor);
      console.log(`🏢 按楼层过滤: ${locations.length} 个结果`);
    }

    console.log(`📤 返回给大屏端的位置数据:`, locations.map(loc => ({
      userId: loc.userId,
      username: loc.username,
      lat: loc.latitude,
      lng: loc.longitude,
      timestamp: new Date(loc.timestamp).toLocaleString()
    })));

    res.json({
      success: true,
      data: {
        locations,
        total: locations.length,
        timestamp: Date.now()
      }
    });
  } catch (error) {
    console.error("获取用户位置失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取特定用户位置
router.get("/users/:userId", authenticateWxAppToken, (req, res) => {
  try {
    const { userId } = req.params;
    const location = userLocations.get(userId);
    
    if (!location) {
      return res.status(404).json({
        success: false,
        message: "用户位置信息不存在"
      });
    }

    res.json({
      success: true,
      data: location
    });
  } catch (error) {
    console.error("获取用户位置失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 用户下线
router.post("/offline", authenticateWxAppToken, (req, res) => {
  try {
    const userId = req.user!.id;
    const location = userLocations.get(userId);
    
    if (location) {
      location.status = 'offline';
      location.lastUpdate = new Date().toISOString();
      userLocations.set(userId, location);
    }

    res.json({
      success: true,
      message: "用户状态已更新为离线"
    });
  } catch (error) {
    console.error("用户下线失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 提交位置需求/请求
router.post("/request", authenticateWxAppToken, (req, res) => {
  try {
    const { type, title, description, targetLocation, priority, estimatedTime } = req.body;
    const userId = req.user!.id;
    const username = req.user!.username || req.user!.name;

    if (!type || !title) {
      return res.status(400).json({
        success: false,
        message: "请求类型和标题为必填项"
      });
    }

    const requestId = `req_${Date.now()}_${userId}`;
    const locationRequest: LocationRequest = {
      id: requestId,
      userId,
      username,
      type,
      title,
      description: description || '',
      priority: priority || 'medium',
      status: 'pending',
      timestamp: Date.now(),
      estimatedTime
    };

    locationRequests.set(requestId, locationRequest);

    res.json({
      success: true,
      message: "位置请求提交成功",
      data: {
        requestId,
        status: 'pending'
      }
    });

    console.log(`新位置请求: ${username} - ${title} (${type})`);
  } catch (error) {
    console.error("提交位置请求失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取位置请求列表
router.get("/requests", authenticateToken, (req, res) => {
  try {
    const { status, type, priority, userId } = req.query;
    
    let requests = Array.from(locationRequests.values());
    
    // 过滤条件
    if (status) {
      const statusArray = Array.isArray(status) ? status : [status];
      requests = requests.filter(req => statusArray.includes(req.status));
    }
    
    if (type) {
      requests = requests.filter(req => req.type === type);
    }
    
    if (priority) {
      requests = requests.filter(req => req.priority === priority);
    }
    
    if (userId) {
      requests = requests.filter(req => req.userId === userId);
    }

    // 按时间倒序排列
    requests.sort((a, b) => b.timestamp - a.timestamp);

    res.json({
      success: true,
      data: {
        requests,
        total: requests.length
      }
    });
  } catch (error) {
    console.error("获取位置请求失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 更新请求状态
router.put("/requests/:requestId", authenticateToken, (req, res) => {
  try {
    const { requestId } = req.params;
    const { status, responseNote } = req.body;
    
    const request = locationRequests.get(requestId);
    if (!request) {
      return res.status(404).json({
        success: false,
        message: "请求不存在"
      });
    }

    request.status = status;
    if (responseNote) {
      (request as any).responseNote = responseNote;
    }
    
    locationRequests.set(requestId, request);

    res.json({
      success: true,
      message: "请求状态更新成功",
      data: request
    });
  } catch (error) {
    console.error("更新请求状态失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

export default router;